package com.xianzhi.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.xianzhi.bean.Ad;
import com.xianzhi.dao.AdDao;
import com.xianzhi.dto.AdDto;
import com.xianzhi.service.AdService;

@Service
public class AdServiceImpl implements AdService {

	@Autowired
	private AdDao adDao;
	
	//@Value注解作用：可以直接根据KEY获取到属性文件中的数据，然后将这个数据赋值给adImageSavePath变量
	//获取到的路径D:/apache-tomcat-7.0.77/webapps/upload/ad/
	@Value("${adImage.savePath}")
	private String adImageSavePath;
	
	@Override
	public boolean add(AdDto adDto) {
		Ad ad = new Ad();
		ad.setTitle(adDto.getTitle());
		ad.setLink(adDto.getLink());
		ad.setWeight(adDto.getWeight());

		if (adDto.getImgFile() != null && adDto.getImgFile().getSize() > 0) {
				//adDto.getImgFile().getOriginalFilename()获取上传文件的名称
				String fileName = System.currentTimeMillis()+"_"+adDto.getImgFile().getOriginalFilename();
				File file = new File(adImageSavePath+fileName);
				File fileFolder = new File(adImageSavePath);
				//如果这个目录不存在
				if(!fileFolder.exists()) {
					//创建目录
					fileFolder.mkdirs();
				}
				try {
					//调用MultipartFile中的transferTo(file)方法将以上创建的文件进行转换并上传。
					adDto.getImgFile().transferTo(file);
					ad.setImgFileName(fileName);
					// insert
					adDao.insert(ad);
					return true;
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
		}
		return false;
	}

	@Override
	public List<AdDto> searchByPage(AdDto adDto) {
		List<AdDto> result = new ArrayList<AdDto>();
		Ad condition = new Ad();
		// bean copy少写了很多set/get方法
		BeanUtils.copyProperties(adDto, condition);
		List<Ad> adList = adDao.selectByPage(condition);
		for (Ad ad : adList) {
			AdDto adDtoTemp = new AdDto();
			result.add(adDtoTemp);
			BeanUtils.copyProperties(ad, adDtoTemp);
		}
		return result;
	}
}
